package data;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;

import user.UserControl;
import user.Loggable;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

import exceptions.DataFileException;


/**
 * This class implements a control system of the database.
 * @author Alexandre, Cristovao, Raul, Rodolpho, Tales
 * @version 1.1
 * @milestone Number 2
 */
public class DataBase {
	
	private final String DATA_FILE = "data.xml";
	
	private static DataBase data = null;
	
	/**
	 * Constructor of the database.
	 */
	protected DataBase(){
		
	}
	
	/**
	 * Implements a Singleton instance of the database of the system
	 * @return data - a single instance of the database
	 */
	public synchronized static DataBase getInstance(){
		if (data == null){
			data = new DataBase();
		}
		return data;
	}
	
	/**
	 * Save DATA in DataBase.
	 * 
	 * @throws DataFileException
	 */
	public void saveData() throws DataFileException {
		XStream xstream = new XStream(new DomDriver());

		xstream.alias("User", Loggable.class);

		String xml = xstream.toXML(UserControl.getInstance().getUsers());

		try {
			File fileAux = new File(DATA_FILE);
			if (fileAux.exists() && fileAux.isFile()) {
				fileAux.delete();
			}

			FileWriter file = new FileWriter(new File(DATA_FILE), true);
			file.write(xml);
			file.close();
		} catch (IOException e) {
			throw new DataFileException(
					"Nao foi possivel salvar os dados no arquivo: " + DATA_FILE);
		}
	}
	
	/**
	 * Load DATA from database.
	 * 
	 * @throws DataFileException
	 *             - if load datas from database occurs any problem, like
	 *             deleted or corrupted file
	 */
	@SuppressWarnings("unchecked")
	public void loadData() throws DataFileException {
		try {
			BufferedReader in = new BufferedReader(new FileReader(DATA_FILE));

			String s;

			StringBuilder sb = new StringBuilder();
			while ((s = in.readLine()) != null) {
				sb.append(s + "\n");
			}
			in.close();
			XStream xstream = new XStream(new DomDriver());
			
			UserControl.getInstance().setUsers((HashMap<String, Loggable>) xstream.fromXML(sb
					.toString()));

		} catch (IOException e) {
			throw new DataFileException(
					"Nao foi possivel ler os dados do arquivo: " + DATA_FILE);
		}

	}
	
	/**
	 * Clean all data in database
	 */
	public void cleanData(){
		File file = new File(DATA_FILE);
		if (file.exists() && file.isFile()) {
			file.delete();
		}
	}

}
